package com.example.a2105_ivideo.livedataTest

import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import java.util.concurrent.atomic.AtomicBoolean

/**
 * @author yaotianxue
 * @description
 * @date 2025/3/12
 */
class SingleLiveData<T>:MutableLiveData<T>(){
    private val pending = AtomicBoolean(false)

    override fun observe(owner: LifecycleOwner, observer: Observer<in T>) {
        super.observe(owner, Observer { t ->
            if (pending.compareAndSet(true, false)) {
                observer.onChanged(t)
            }
        })
    }


    /**
     * 主线程设置数据
     */
    override fun setValue(value: T) {
        pending.set(true)
        super.setValue(value)
    }

    /**
     * 子线程设置数据
     */

    override fun postValue(value: T) {
        pending.set(true)
        super.postValue(value)
    }

}